<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.6.8/angular.min.js"></script>
  </head>
  <body>
    <div ng-app="myApp" ng-controller="myCtrl">
      <h1>{{indexName}}</h1>
      <!-- 自定义组件 -->
      <hello></hello>
    </div>

    <script>
      var app = angular.module("myApp", []);
      app.controller("myCtrl", function ($scope) {
        $scope.indexName = "主页";
      });
      // 第一个组件
      app.component("hello", {
        template: `
            <div>
                <h3>Hello</h3>
                <world1></world1>
                <world2></world2>
            </div>
        `,
        controller: function ($scope) {
          this.$onInit = function () {
          };
          // 父级监听发送的数据
          $scope.$on("toParent",function(event,data){
            console.log("Hello",data);
            // 向下级发送数据
            $scope.$broadcast("toChildren",data)
          })
          // 父级监听发送到子级的数据,不会触发
          $scope.$on("toChild",function(event,data){
            console.log("parent_childdata",data);
          })
        },
      });
      // 第二个组件
      app.component("world1", {
        template: `
            <div>
                <h4>World1</h4>
                <button ng-click="$ctrl.submit()">发送数据</button>
            </div>
        `,
        controller: function ($scope) {
          this.$onInit = function () {
          };
          this.submit = function () {
            // 向父级发送数据
            $scope.$emit("toParent","parent_msg");
          }
        },
      });
      // 第三个组件，为兄弟组件
      app.component("world2", {
        template: `
            <div>
                <h4>World2</h4>
            </div>
        `,
        controller: function ($scope) {
          this.$onInit = function () {
          };
          // 监听父级发送的数据
          $scope.$on("toChildren",function(event,data){
            console.log("World2",data);
          })
        },
      });
    </script>
  </body>
</html>
